﻿using IterationLife.Datas;
using IterationLife.FootballTeaching.Models;
using IterationLife.FootballTeaching.Queries;
using IterationLife.FootballTeaching.Repositories;
using IterationLife.PlatformBackEnd.AppServices.Contracts.FootballTeachings;
using IterationLife.PlatformBackEnd.AppServices.Dtos.FootballTeachings;
using Util;
using Util.Applications;
using Util.Datas.Queries;
using Util.Exceptions;

namespace IterationLife.PlatformBackEnd.AppServices.Impl.FootballTeachings
{
    /// <summary>
    /// 课程服务
    /// </summary>
    public class CourseService : ApplicationServiceBase<Course, CourseDto, CourseQuery>, ICourseService
    {
        /// <summary>
        /// 初始化课程服务
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        /// <param name="courseRepository">课程仓储</param>
        public CourseService(IApplicationUnitOfWork unitOfWork, ICourseRepository courseRepository)
            : base(unitOfWork, courseRepository)
        {
            CourseRepository = courseRepository;
        }

        /// <summary>
        /// 课程仓储
        /// </summary>
        protected ICourseRepository CourseRepository { get; set; }

        /// <summary>
        /// 转换为数据传输对象
        /// </summary>
        /// <param name="entity">实体</param>
        protected override CourseDto ToDto(Course entity)
        {
            return entity.ToDto();
        }

        /// <summary>
        /// 转换为实体
        /// </summary>
        /// <param name="dto">数据传输对象</param>
        protected override Course ToEntity(CourseDto dto)
        {
            return dto.ToEntity();
        }

        /// <summary>
        /// 创建查询对象
        /// </summary>
        /// <param name="param">课程查询实体</param>
        protected override IQueryBase<Course> CreateQuery(CourseQuery param)
        {
            return new Query<Course>(param)
                .Filter(t => t.Name.Contains(param.Name));
        }

        /// <summary>创建实体</summary>
        public override CourseDto Create()
        {
            var dto = base.Create();
            return dto.Init(CourseRepository.GetSortId());
        }

        /// <summary>保存前操作</summary>
        /// <param name="dto">数据传输对象</param>
        protected override void SaveBefore(CourseDto dto)
        {
            if (dto.Banner.Id.IsEmpty())
                throw new Warning("请上传封面图");
            if (dto.CourseCategories.Count == 0)
                throw new Warning("至少选择一个分类");
            if (dto.PlayerPositions.Count == 0)
                throw new Warning("至少选择一个球员位置");
            base.SaveBefore(dto);
        }
    }
}